package yunjiao.javatutorials.guava.concurrent.event;

import com.google.common.util.concurrent.ListenableFuture;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 超时控制
 *
 * @author yangyunjiao
 */
public class TimeoutControlExample {
    public static void main(String[] args) {
        EventProcessor processor = new EventProcessor();

        ListenableFuture<String> future = processor.sendRequest("TIMEOUT-001", "长时间操作");

        // 模拟长时间不响应
        new Thread(() -> {
            try {
                Thread.sleep(5000); // 5秒后才响应
                processor.handleResponse("TIMEOUT-001", "延迟响应");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();

        try {
            // 设置超时时间为2秒
            String result = future.get(2, TimeUnit.SECONDS);
            System.out.println("收到结果: " + result);
        } catch (TimeoutException e) {
            System.out.println("请求超时，清理资源");
            processor.cleanupRequest("TIMEOUT-001");
        } catch (Exception e) {
            System.out.println("其他错误: " + e.getMessage());
        }

        System.out.println("最终剩余请求数: " + processor.getPendingRequestCount());
    }
}
